﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FlashPay.Service.Impl
{
    using AutoMapper;
    using FlashPay.DAO.Bank;
    using FlashPay.DAO.Interface;
    using FlashPay.DAO.Sys;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.DepositMatchRule;
    using FlashPay.Entity.Response.Bank;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Entity.Response.DepositMatchRule;
    using FlashPay.Entity.Response.Sys;
    using FlashPay.Service.Interface;
    using Newtonsoft.Json;
    using System.Linq;
    using System.Text.RegularExpressions;

    /// <summary>
    /// 收款匹配规则业务接口实现
    /// </summary>
    public class DepositMatchRuleServiceImpl : DepositMatchRuleService
    {
        #region 注入
        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly DepositMatchRuleDao _depositMatchRuleDao;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        public readonly BankInfoDAO _bankInfoDao;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankDao _bankDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly UserInfoDao _userInfoDao;

        /// <summary>
        /// 系统配置接口
        /// </summary>
        private readonly SysConfigDao _sysConfigDao;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="menu">收款匹配规则业务接口</param>
        public DepositMatchRuleServiceImpl(DepositMatchRuleDao depositMatchRuleDao, BankInfoDAO bankInfoDao, BankDao bankDao, CompanyDao companyDao, UserInfoDao userInfoDao, SysConfigDao sysConfigDao, LogDao logDao, LogRecord logRecord, IMapper mapper)
        {
            _depositMatchRuleDao = depositMatchRuleDao;
            _bankInfoDao = bankInfoDao;
            _bankDao = bankDao;
            _companyDao = companyDao;
            _userInfoDao = userInfoDao;
            _sysConfigDao = sysConfigDao;
            _logRecord = logRecord;
            _logDao = logDao;
            _mapper = mapper;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        public DepositMatchRuleResponse Get(int id, int companyId)
        {
            var depositMatchRuleResponse = new DepositMatchRuleResponse();

            var depositMatchRule = _depositMatchRuleDao.Get(id);
            if (depositMatchRule != null)
            {
                depositMatchRuleResponse.Id = depositMatchRule.Id;
                depositMatchRuleResponse.CompanyId = depositMatchRule.CompanyId;
                depositMatchRuleResponse.MatchMinusMinute = depositMatchRule.MatchMinusMinute;
                depositMatchRuleResponse.MatchMinute = depositMatchRule.MatchMinute;
                depositMatchRuleResponse.MatchBankCode = depositMatchRule.MatchBankCode;
                depositMatchRuleResponse.MatchTranstype = depositMatchRule.MatchTranstype;
                depositMatchRuleResponse.MatchRule = depositMatchRule.MatchRule;
                depositMatchRuleResponse.MatchPushRule = depositMatchRule.MatchPushRule;
                depositMatchRuleResponse.MatchRemark = depositMatchRule.MatchRemark;
                depositMatchRuleResponse.CreateId = depositMatchRule.CreateId;
                depositMatchRuleResponse.CreateDate = depositMatchRule.CreateDate;
            }

            #region 银行
            var bankInfoResponses = new List<BankInfoResponse>();

            var bankInfos = _bankInfoDao.GetBankInfoList();
            if (bankInfos != null && bankInfos.Any())
            {
                bankInfos.ForEach(item =>
                {
                    bankInfoResponses.Add(new BankInfoResponse()
                    {
                        BankCode = item.BankCode,
                        BankName = item.BankName
                    });
                });

                depositMatchRuleResponse.BankInfoResponse = bankInfoResponses;
            }
            #endregion

            #region 公司列表
            var companys = this.GetCompany(companyId);

            var companyResponse = new List<CompanyResponse>();
            if (companys != null && companys.Any())
            {
                foreach (var item in companys)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyID,
                        CompanyName = item.CompanyName,
                    });
                }
                depositMatchRuleResponse.CompanyResponse = companyResponse;
            }
            #endregion

            #region 配置列表
            List<SysConfigResponse> SysConfigTypeList = new List<SysConfigResponse>();

            var q = _sysConfigDao.GetTransTypeList(new FlashPay.Entity.Request.Sys.SysConfigAddOrEditRequest { ConfigCode = "Transtype" });//配置列表
            q.ForEach(item =>
            {
                SysConfigTypeList.Add(new SysConfigResponse()
                {
                    ConfigId = item.ConfigId,
                    ConfigCode = item.ConfigCode,
                    ConfigValue = item.ConfigValue,
                    ConfigContent = item.ConfigContent,
                    CompanyId = item.CompanyId,
                    Description = item.Description
                });
            });
            depositMatchRuleResponse.SysConfigTypeList = SysConfigTypeList;
            #endregion 配置列表

            return depositMatchRuleResponse;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public List<CompanyResponse> GetCompany(int companyId, int level = 2)
        {
            return _bankDao.GetCompany(companyId, level);
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult DepositMatchRuleAddOrEdit(DepositMatchRuleAddOrEditRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                #region 数据验证
                if (request.CompanyId <= 0)
                {
                    throw new Exception("请选择公司！");
                }

                if (!string.IsNullOrEmpty(request.MatchMinusMinute))
                {
                    var matchMinusMinuteReg = new Regex(@"^((^-[1-9]\d{0,3})|0)?$");
                    if (!matchMinusMinuteReg.IsMatch(request.MatchMinusMinute))
                    {
                        throw new Exception("匹配时间(-分)介于 -1440 和 0 之间");
                    }

                    if (int.Parse(request.MatchMinusMinute) > 0 || int.Parse(request.MatchMinusMinute) < -1440)
                    {
                        throw new Exception("匹配时间(-分)介于 -1440 和 0 之间");
                    }
                }

                if (string.IsNullOrEmpty(request.MatchMinute))
                {
                    throw new Exception("匹配时间(分)不能为空！");
                }

                var matchMinuteReg = new Regex(@"^[0-9]*[1-9][0-9]*$");
                if (!matchMinuteReg.IsMatch(request.MatchMinute.ToString()))
                {
                    throw new Exception("匹配时间(分)介于 10 和 1440 之间");
                }

                if (int.Parse(request.MatchMinute) < 10 || int.Parse(request.MatchMinute) > 1440)
                {
                    throw new Exception("匹配时间(分)介于 10 和 1440 之间");
                }
                #endregion

                #region 匹配规则
                if (request.MatchRule != null && request.MatchRule.Count > 0)
                {
                    var nameExit = request.MatchRule.Contains(MatchRule.姓名.GetHashCode());
                    var amountExit = request.MatchRule.Contains(MatchRule.金额.GetHashCode());
                    if (!nameExit && !amountExit)
                    {
                        throw new Exception("匹配规则姓名与金额,两个必须需选一个！");
                    }
                }
                else
                {
                    throw new Exception("匹配规则姓名与金额,两个必须需选一个！");
                }
                #endregion

                #region  推送条件
                var matchPushRule = request.MatchPushSuccess + request.MatchPushFail;
                if (matchPushRule <= 0) {
                    throw new Exception("推送条件必须选择一项");
                }
                #endregion

                #region 银行、存款类型验证

                

                #region 获取当前公司公司的银行编码
                var depositMatchRules = _depositMatchRuleDao.GetList(new DepositMatchRuleQuery() { NotEqualId = request.Id, CompanyId = request.CompanyId });
                if (depositMatchRules != null && depositMatchRules.Any())
                {
                    depositMatchRules.ForEach(item =>
                    {
                        var isExistBank = false;
                        //存在银行编码
                        var bankCode = new List<string>();
                        //存在交易类型
                        var transType = new List<int>();

                        if (!string.IsNullOrEmpty(item.MatchBankCode))
                        {
                            var ruleArray = item.MatchBankCode.Split(',');
                            if (ruleArray != null && ruleArray.Any())
                            {
                                foreach (var code in ruleArray)
                                {
                                    if (!bankCode.Contains(code)) {
                                        bankCode.Add(code);
                                    }
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(item.MatchTranstype))
                        {
                            var ruleArray = item.MatchTranstype.Split(',');
                            if (ruleArray != null && ruleArray.Any())
                            {
                                foreach (var type in ruleArray)
                                {
                                    if (!transType.Contains(Convert.ToInt32(type))) {
                                        transType.Add(Convert.ToInt32(type));
                                    }
                                }
                            }
                        }


                        if (request.MatchBankCode != null && request.MatchBankCode.Any())
                        {
                            foreach (var matchBankCode in request.MatchBankCode)
                            {
                                if (bankCode.Contains(matchBankCode))
                                {
                                    isExistBank = true;
                                    break;
                                }
                            }
                        }

                        if (request.MatchTranstype != null && request.MatchTranstype.Any())
                        {
                            foreach (var matchTranstype in request.MatchTranstype)
                            {
                                if (transType.Contains(matchTranstype) && isExistBank)
                                {
                                    throw new Exception("同一家银行无法添加重复的交易类型！");
                                }
                            }
                        }
                    });
                }
                #endregion

               
                //比较
                //if (request.MatchBankCode != null && request.MatchBankCode.Any())
                //{
                //    foreach (var item in request.MatchBankCode)
                //    {
                //        if (bankCode.Contains(item))
                //        {
                //            isExistBank = true;
                //            break;
                //        }
                //    }
                //}
                

                //if (request.MatchTranstype != null && request.MatchTranstype.Any())
                //{
                //    foreach (var item in request.MatchTranstype)
                //    {
                //        if (transType.Contains(item) && isExistBank)
                //        {
                //            throw new Exception("同一家银行无法添加重复的交易类型！");
                //        }
                //    }
                //}
                #endregion

                var depositMatchRule = new DepositMatchRule();
                if (request.Id > 0)
                {
                    depositMatchRule = _depositMatchRuleDao.Get(request.Id);
                    if (depositMatchRule == null)
                    {
                        throw new Exception("修改记录不存在！");
                    }
                }
                var requestData = JsonConvert.SerializeObject(depositMatchRule);

                depositMatchRule.CompanyId = request.CompanyId;
                if (!string.IsNullOrEmpty(request.MatchMinusMinute)) {
                    depositMatchRule.MatchMinusMinute = Int32.Parse(request.MatchMinusMinute);
                }
                depositMatchRule.MatchMinute = Int32.Parse(request.MatchMinute);
                depositMatchRule.MatchBankCode = request.MatchBankCode == null ? "" : string.Join(",", request.MatchBankCode);
                depositMatchRule.MatchRule = string.Join(",", request.MatchRule);
                depositMatchRule.MatchPushRule = Convert.ToSByte(matchPushRule);
                depositMatchRule.MatchRemark = request.MatchRemark;
                depositMatchRule.MatchTranstype = request.MatchTranstype == null ? "" : string.Join(",", request.MatchTranstype);

                if (request.Id > 0)
                {
                    var updateStatus = _depositMatchRuleDao.Update(depositMatchRule);
                    if (!updateStatus)
                    {
                        throw new Exception("更新失败");
                    }

                    //日志
                    _logRecord.LogType = LogRecordLogType.DepositMatchRule_Edit.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"修改收款匹配规则成功,编号:{request.Id}";
                    _logRecord.RequestData = requestData;
                    _logRecord.AffectData = JsonConvert.SerializeObject(depositMatchRule);
                    _logDao.Insert(_logRecord);

                    result.SuccessMessage = "编辑收款匹配规则成功";
                    result.Success = true;
                }
                else
                {
                    depositMatchRule.CreateId = request.CreateId;
                    depositMatchRule.CreateDate = DateTime.Now;
                    var addStatus = _depositMatchRuleDao.Add(depositMatchRule);
                    if (addStatus <= 0)
                    {
                        throw new Exception("新增失败");
                    }

                    //日志
                    _logRecord.LogType = LogRecordLogType.DepositMatchRule_Add.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"新增收款匹配规则成功,编号:{addStatus}";
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "新增收款匹配规则成功";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <returns></returns>
        public JResult Delete(int id, int companyId)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var depositMatchRule = _depositMatchRuleDao.Get(id);
                if (depositMatchRule == null)
                {
                    throw new Exception("删除记录不存在！");
                }

                var userInfo = _userInfoDao.Get(depositMatchRule.CreateId);
                if (userInfo == null)
                {
                    throw new Exception("删除记录的用户不存在！");
                }

                #region 公司条件过滤
                var companyIds = new List<int>();
                //var companyIds = _bankDao.GetCompanyIDList(companyId);
                var companys = this.GetCompany(companyId, 2);
                if (companys != null && companys.Any())
                {
                    companys.ForEach(item =>
                    {
                        companyIds.Add(item.CompanyID);
                    });
                }

                if (!companyIds.Contains(userInfo.UCompanyId))
                {
                    throw new Exception("改记录不属于当前公司及子公司操作权限！");
                }
                #endregion

                var deleteStatus = _depositMatchRuleDao.Delete(id);
                if (deleteStatus)
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.DepositMatchRule_Delete.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"删除收款匹配规则成功,编号:{id}";
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "删除成功！";
                }
                else
                {
                    result.Success = false;
                    result.SuccessMessage = "删除失败！";
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<DepositMatchRule> GetList(DepositMatchRuleQuery query)
        {
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<Permission></returns>
        public PagedList<DepositMatchRuleResponse> GetPager(DepositMatchRuleQuery query)
        {
            query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            PagedList<DepositMatchRuleResponse> pag = _depositMatchRuleDao.GetPager(query);

            #region 数据转换
            if (pag.Success)
            {
                List<DepositMatchRuleResponse> list = pag.TData.ToList();

                var bankInfos = _bankInfoDao.GetBankInfoList();

                for (int i = 0; i < pag.TData.Count; i++)
                {
                    #region 媒合规则
                    if (!string.IsNullOrEmpty(pag.TData[i].MatchRule))
                    {
                        var matchRules = new List<string>();

                        var matchRuleArray = pag.TData[i].MatchRule.Split(',');
                        if (matchRuleArray != null && matchRuleArray.Any())
                        {
                            foreach (var rule in matchRuleArray)
                            {
                                var ruleText = (MatchRule)int.Parse(rule);
                                matchRules.Add(ruleText.ToString());
                            }
                        }
                        if (matchRules != null && matchRules.Count > 0)
                        {
                            pag.TData[i].MatchRule = string.Join(",", matchRules);
                        }
                    }
                    #endregion

                    #region 收款银行
                    if (!string.IsNullOrEmpty(pag.TData[i].MatchBankCode))
                    {
                        var matchBankCodes = new List<string>();

                        var matchBankCodeArray = pag.TData[i].MatchBankCode.Split(',');
                        if (matchBankCodeArray != null && matchBankCodeArray.Any())
                        {
                            foreach (var bankCode in matchBankCodeArray)
                            {
                                var bankInfo = bankInfos.FirstOrDefault(p => p.BankCode == bankCode);
                                if (bankInfo != null)
                                {
                                    matchBankCodes.Add(bankInfo.BankName);
                                }
                            }
                            if (matchBankCodes != null && matchBankCodes.Count > 0)
                            {
                                pag.TData[i].MatchBankCode = string.Join(",", matchBankCodes);
                            }
                        }
                    }
                    #endregion

                    pag.TData[i].MatchTranstypeName = GetConfigNameByStr(pag.TData[i].MatchTranstype);
                }
            }
            #endregion

            return pag;
        }

        //根据matchTranstype字符串查询配置内容
        public string GetConfigNameByStr(string matchTranstype)
        {
            if (string.IsNullOrEmpty(matchTranstype)) return "";

            List<string> list = matchTranstype.Split(',').ToList();
            if (list.Count <= 0) return "";

            List<int> newList = list.Select(x => int.Parse(x)).ToList();
            var item = _sysConfigDao.GetList(new SysConfigQuery { TypeIds = newList, ConfigCode = "Transtype" }).Distinct().Select(e => e.ConfigContent).ToList();

            if (item == null || item.Count <= 0) return "";

            string newStr = string.Empty;
            for (int z = 0; z < item.Count; z++)
            {
                newStr += item[z] + ",";
            }
            newStr = newStr.TrimEnd(',');
            return newStr;
        }

        /// <summary>
        /// 根据companyId、bankcode查询匹配规则
        /// </summary>
        /// <param name="id">编号</param>
        public JResult<DepositMatchRule> GetRuleByCompanyId(int companyId, string bankcode)
        {
            var response = new JResult<DepositMatchRule>()
            {
                Success = false
            };
            try
            {
                var depositMatchRule = _depositMatchRuleDao.GetRuleByCompanyId(companyId, bankcode);
                response.Success = true;
                response.Data = depositMatchRule;
                return response;
            }
            catch (Exception)
            {
                response.ErrorMessage = "服务器错误";
            }
            return response;
        }

    }
}
